///@Description(描述)     测试BaseLogic的Logic类
///@author(作者)          zhangyinhong
///@create(时间)          2025-01-20 10:30

import 'package:app_core/app_core.dart';
import 'package:get/get.dart';
import 'app_base_logic.dart';

/// 测试页面的更新key枚举（模拟您的LoginUpdateKey模式）
enum BaseTestUpdateKey {
  pageState,    // 页面状态专用ID（用于loading/error/empty状态）
  counter,      // 计数器
  userInfo,     // 用户信息
  todoList,     // 待办列表
}

/// 模拟的用户信息Model
class UserInfo {
  final String name;
  final String email;
  final String avatar;

  UserInfo({required this.name, required this.email, required this.avatar});
}

/// 模拟的待办事项Model
class TodoItem {
  final String id;
  final String title;
  final bool isCompleted;

  TodoItem({required this.id, required this.title, required this.isCompleted});

  TodoItem copyWith({String? title, bool? isCompleted}) {
    return TodoItem(
      id: id,
      title: title ?? this.title,
      isCompleted: isCompleted ?? this.isCompleted,
    );
  }
}

class BaseTestLogic extends AppBaseLogic {
  /// 计数器 - 改为响应式变量
  final counter = 0.obs;

  /// 用户信息 - 改为响应式变量
  final userInfo = Rx<UserInfo?>(null);

  /// 待办列表 - 改为响应式变量
  final todoList = <TodoItem>[].obs;
  
  /// 当前页码（用于模拟分页加载）
  final currentPage = 1.obs;
  
  /// 是否还有更多数据
  final hasMore = true.obs;

  @override
  void onInit() {
    super.onInit();
    YHLog.i('BaseTestLogic初始化');
    
    loadInitialData();
  }

  /// 模拟初始数据加载
  Future<void> loadInitialData({bool isRefresh = false}) async {
    YHLog.i('开始加载初始数据，刷新模式：$isRefresh');
    
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      if (isRefresh) {
        userInfo.value = UserInfo(
          name: '张三',
          email: 'zhangsan@example.com',
          avatar: 'https://avatar.example.com/zhangsan.jpg',
        );
        
        todoList.clear();
        currentPage.value = 1;
        hasMore.value = true;
        todoList.addAll([
          TodoItem(id: '1', title: '完成项目需求分析', isCompleted: true),
          TodoItem(id: '2', title: '编写技术文档', isCompleted: false),
          TodoItem(id: '3', title: '代码review', isCompleted: false),
          TodoItem(id: '4', title: '单元测试', isCompleted: true),
        ]);
      } else {
        final random = DateTime.now().millisecond % 3;
        
        if (random == 0) {
          throw Exception('网络连接失败，请检查网络设置');
        } else if (random == 1) {
          userInfo.value = UserInfo(
            name: '测试用户',
            email: 'test@example.com',
            avatar: 'https://avatar.example.com/test.jpg',
          );
          todoList.clear(); // 空列表
        } else {
          userInfo.value = UserInfo(
            name: '张三',
            email: 'zhangsan@example.com',
            avatar: 'https://avatar.example.com/zhangsan.jpg',
          );
          
          todoList.clear();
          currentPage.value = 1;
          hasMore.value = true;
          todoList.addAll([
            TodoItem(id: '1', title: '完成项目需求分析', isCompleted: true),
            TodoItem(id: '2', title: '编写技术文档', isCompleted: false),
            TodoItem(id: '3', title: '代码review', isCompleted: false),
            TodoItem(id: '4', title: '单元测试', isCompleted: true),
          ]);
        }
      }
    } catch (e) {
      YHLog.e('加载数据失败: $e');
      YHSmartDialog.showErrorMsg(e.toString());
    }
  }

  /// 重试方法
  @override
  Future<void> onRetry() async {
    YHLog.i('用户点击重试');
    await loadInitialData();
  }

  /// 刷新方法
  @override
  Future<void> onRefresh() async {
    YHLog.i('用户下拉刷新');
    
    try {
      currentPage.value = 1;
      hasMore.value = true;
      
      await loadInitialData(isRefresh: true);
      
      YHLog.i('下拉刷新完成');
    } catch (e) {
      YHLog.e('下拉刷新失败', error: e);
      rethrow;
    }
  }

  /// 增加计数器（局部刷新示例）
  void incrementCounter() {
    counter.value++;
    YHLog.i('计数器增加到：${counter.value}');
  }

  /// 减少计数器
  void decrementCounter() {
    if (counter.value > 0) {
      counter.value--;
      YHLog.i('计数器减少到：${counter.value}');
    }
  }

  /// 切换待办事项状态
  void toggleTodoItem(String id) {
    final index = todoList.indexWhere((item) => item.id == id);
    if (index != -1) {
      todoList[index] = todoList[index].copyWith(
        isCompleted: !todoList[index].isCompleted,
      );
      YHLog.i('切换待办事项：${todoList[index].title} -> ${todoList[index].isCompleted}');
    }
  }

  /// 添加新的待办事项
  void addTodoItem(String title) {
    if (title.trim().isNotEmpty) {
      final newItem = TodoItem(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: title.trim(),
        isCompleted: false,
      );
      todoList.add(newItem);
      YHLog.i('添加新待办事项：$title');
    }
  }

  /// 删除待办事项
  void deleteTodoItem(String id) {
    todoList.removeWhere((item) => item.id == id);
    YHLog.i('删除待办事项：$id');
  }

  /// 模拟更新用户信息
  void updateUserName(String newName) {
    if (newName.trim().isNotEmpty && userInfo.value != null) {
      userInfo.value = UserInfo(
        name: newName.trim(),
        email: userInfo.value!.email,
        avatar: userInfo.value!.avatar,
      );
      YHLog.i('更新用户名：$newName');
    }
  }

  /// 上拉加载更多
  @override
  Future<void> onLoadMore() async {
    YHLog.i('用户上拉加载更多');
    if (!hasMore.value) return;
    try {
      await Future.delayed(const Duration(seconds: 1));
      
      currentPage.value++;
      
      final moreItems = [
        TodoItem(id: '${currentPage.value}_1', title: '第${currentPage.value}页任务1', isCompleted: false),
        TodoItem(id: '${currentPage.value}_2', title: '第${currentPage.value}页任务2', isCompleted: false),
        TodoItem(id: '${currentPage.value}_3', title: '第${currentPage.value}页任务3', isCompleted: true),
      ];
      todoList.addAll(moreItems);
      if (currentPage.value >= 3) {
        hasMore.value = false;
      }
      
      YHLog.i('加载更多完成，当前页：${currentPage.value}，总数：${todoList.length}');
      
    } catch (e) {
      YHLog.e('加载更多失败', error: e);
    }
  }

  @override
  void onClose() {
    YHLog.i('BaseTestLogic销毁');
    super.onClose();
  }
}
